'use strict';
const db = uniCloud.database()
const ordersCollection = db.collection('orders')
const $ = db.command.aggregate

exports.main = async (event, context) => {
	const { userId, status } = event
	
	try {
		if (!userId) {
			return {
				code: -1,
				msg: '用户ID不能为空'
			}
		}
		
		// 构建查询条件
		const matchStage = {
			userId,
		}
		
		// 如果指定了状态，添加状态筛选
		if (status) {
			matchStage.status = parseInt(status) // 确保状态是数字类型
		}
		
		// 聚合查询订单信息和关联的课程信息
		const orders = await ordersCollection
			.aggregate()
			.match(matchStage)
			.lookup({
				from: 'courses',
				localField: 'courseId',
				foreignField: '_id',
				as: 'courseInfo'
			})
			.project({
				_id: 1,
				courseId: 1,
				status: 1,
				createTime: 1,
				price: 1,
				courseInfo: $.arrayElemAt(['$courseInfo', 0])
			})
			.sort({
				createTime: -1
			})
			.end()
		
		return {
			code: 0,
			msg: '获取成功',
			data: orders.data
		}
	} catch (e) {
		return {
			code: -1,
			msg: '获取失败',
			error: e
		}
	}
}; 